package org.raymond.iworks.study.netty.atguigu.netty.heatbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class HeatbeatServer {
    public static void main(String[] args) throws Exception {
        int port = 6666;
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup(2);
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup)
                    .option(ChannelOption.SO_BACKLOG, 128) // tcp/ip协议,listen函数中的backlog参数,用来初始化服务端可连接队列
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 保持连接
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    // netty提供的处理空闲状态的handler
                                    // readerIdleTime: server端有多长时间没有读到客户端发送的数据,就会触发一个idleStateEvent事件,
                                    // 其实就是发送一个心跳检测包
                                    // writerIdleTime: 表示多长时间没有向客户端写数据...
                                    // allIdleTime: 表示多长时间即没用读也没有写...
                                    // 有时对端连接断开,服务端无法感知到 (tcp的keeplive主要用于保活和检测死链)
                                    // 当IdleStateEvent触发后,会传递给管道的下一个handler,
                                    // 由下一个handler调用userEventTrigger方法去处理
                                    .addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS))
                                    .addLast(new HeatbeatServerHandler())
                            ;
                        }
                    });
            // 绑定并启动
            ChannelFuture future = bootstrap.bind(port).sync();
            future.addListener(f -> {
                if(f.isSuccess()){
                    log.info("监听端口{}成功", port);
                }else{
                    log.info("监听端口{}失败", port);
                }
            });
            // 对关闭通道进行监听
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
